package com.cheyun.netsalev3.viewmodel

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Environment
import android.os.Looper
import android.print.PrintAttributes
import android.print.PrintManager
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Transformations
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.MyPrintAdapter
import com.cheyun.netsalev3.bean.FollowParam
import com.cheyun.netsalev3.bean.drive.DriveListInfo
import com.cheyun.netsalev3.bean.drive.Reservemit
import com.cheyun.netsalev3.repository.DriveListPageRepository
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.utils.CommonFunc
import com.cheyun.netsalev3.utils.DownloadUtil
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.api.ApiStores
import com.cheyun.netsalev3.view.AddClueActivity
import com.cheyun.netsalev3.view.AddDriveActivity
import com.cheyun.netsalev3.view.CarDriveDetailsActivity2
import com.cheyun.netsalev3.view.defeatdetails.DefeatDetailsActivity
import com.cheyun.netsalev3.widget.MyContentDialog
import com.cheyun.netsalev3.widget.MyContentDialogLayout
import com.cheyunkeji.er.utils.ToastUtil
import com.dou361.dialogui.DialogUIUtils
import com.tbruyelle.rxpermissions3.RxPermissions
import java.io.File
import java.io.Serializable

class DriveListViewModel(var repository: DriveListPageRepository) : BaseViewModel() {
     var items= repository.loadAndroidData()

    val networkState = Transformations.switchMap(items) { repository.networkState }!!
    val total = Transformations.switchMap(items) { repository.total }!!

    fun onclickItem(view: View, item: DriveListInfo) {
//        var intent = Intent(view.context, StockDetailsActivity::class.java)
//        intent.putExtra("id",item.id)
//        view.context.startActivity(intent)
    }

    var url = ""
    var currentContext:Context? = null

    fun refresh(){
        repository.dataSourceFactory.sourceLiveData.value?.invalidate()
    }

    fun onClickStop(view:View,item:DriveListInfo){
        var moth: () -> Unit = {
            refresh()
        }
        var fail: () -> Unit = {

        }
        repository.driveend(item.id,MySharedPreferences.getLoginData()?.member?.uid!!,moth,fail)
    }

    fun onClickCancel(view:View,item:DriveListInfo){
        var moth: () -> Unit = {
            refresh()
        }
        var fail: () -> Unit = {

        }
        repository.cancelDrive(item.id,moth,fail)
    }

    var follow:FollowParam?=null
    var context: Context? = null

    fun onClickDetail(view:View,item:DriveListInfo){
//        var intent = Intent(view.context, DefeatDetailsActivity::class.java)
//        intent.putExtra("tid", item.tid)
//        intent.putExtra("nkey", "archive.purge")
//        view.context.startActivity(intent)
        if(!item.tid.equals("0")){
            var intent = Intent(view.context, DefeatDetailsActivity::class.java)
            intent.putExtra("tid", item.tid)
            intent.putExtra("nkey", "archive.index")
//                    //来源：客流接待
//                    intent.putExtra("come", "keliu")
//                    intent.putExtra("keliudata", item as Serializable)
            view.context.startActivity(intent)
        }else{
            this.context = view.context

            var moth: (it: FollowParam) -> Unit = {
                this.follow = it
                when (it.revkey) {
                    "add" -> {
                        var intent = Intent(view.context, AddClueActivity::class.java)
                        intent.putExtra("name", item.uname)
                        intent.putExtra("phone", item.phone)
                        intent.putExtra("sex", item.sex)
//                    //来源：客流接待
//                    intent.putExtra("come", "keliu")
//                    intent.putExtra("keliudata", item as Serializable)
                        view.context.startActivity(intent)
                    }
                    "bazaar" ->{
                        MyToast(it.msg)
                    }
                    "owner" -> {
                        MyToast(it.msg)
                    }
                    "check" ->{
                        MyToast(it.msg)
                    }
                    "follow" -> {
                        var intent = Intent(view.context, DefeatDetailsActivity::class.java)
                        intent.putExtra("tid", it.tid)
                        intent.putExtra("nkey", "archive.index")
//                    //来源：客流接待
//                    intent.putExtra("come", "keliu")
//                    intent.putExtra("keliudata", item as Serializable)
                        view.context.startActivity(intent)
                    }
                    "followtip" ->{
                        var context = view.context
                        if (context is AppCompatActivity) {
                            var pop = MyContentDialog.newInstance("线索跟进", it.msg +
                                    "是否跟进？")
                            pop.onClickOk = this::popOk
                            pop.show(context.supportFragmentManager, "")
                        }
                    }
                    else -> {
                        var context = view.context
                        if (context is AppCompatActivity) {
                            var pop = MyContentDialog.newInstance("潜客激活", "该客户电话已经存在潜客(战败)," +
                                    "是否激活潜客数据？")
                            pop.onClickOk = this::popOk
                            pop.show(context.supportFragmentManager, "")
                        }
                    }
                }
            }
            repository.getfollow(item.rid, moth)
        }
    }

    fun onClickDriveDetail(view:View,item:DriveListInfo){
        if(item.state == 1){
            //已预约的跳转到编辑
            var content = view.context
            if (content is AppCompatActivity) {

                var moth: (detail:DriveListInfo) -> Unit = {
                    it.reservehalfStr = it.reservehalf.joinToString(",")
                    var intent = Intent(view.context, AddDriveActivity::class.java)
                    intent.putExtra("data", it as Serializable)
                    view.context.startActivity(intent)
                }
                var fail: () -> Unit = {

                }
                repository.getDriveDetail(item.id,moth,fail)
            }
        }else {
            var intent = Intent(view.context, CarDriveDetailsActivity2::class.java)
            intent.putExtra("id", item.id)
            view.context.startActivity(intent)
        }
    }

    fun onCopyTel(view:View,item:DriveListInfo){
        if (item?.phone?.indexOf("*") == -1) {
            CommonFunc.copy(view.context, item?.phone)
            ToastUtil.showToast("复制成功")
        } else {
            ToastUtil.showToast("当前号码不能复制")
        }
    }

    fun onPrint(view:View,item:DriveListInfo){
        context = view.context

        RxPermissions(context as AppCompatActivity).requestEach(
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe {
            if (it.granted) {
                enablePrint(item.id)
            } else if (it.shouldShowRequestPermissionRationale) {
                DemoLog.e("WRITE_EXTERNAL_STORAGE", "shouldShowRequestPermissionRationale")
            } else {
                DemoLog.e("WRITE_EXTERNAL_STORAGE", "error")
            }
        }
    }
    fun enablePrint(id:Int){
        var dialog = DialogUIUtils.showLoadingVertical(context, "加载中...",false,false,false).show()
        var moth: (data: Reservemit) -> Unit = {
            DialogUIUtils.dismiss(dialog)
            if (context is AppCompatActivity) {
                currentContext = context
                url = ApiStores.API_SERVER_URL+ it.print
                var dialog = MyContentDialogLayout.newInstance("打印登记关怀单", R.layout.print_layout)
                dialog.onClickOk = this@DriveListViewModel::confirmPrint
                dialog.onClickCancel = this@DriveListViewModel::cancelPrint
                dialog.show((context as AppCompatActivity).supportFragmentManager, "")
            }
        }
        var fail: () -> Unit = {
            DialogUIUtils.dismiss(dialog)
        }

        repository.print(id,moth,fail)
    }


    fun confirmPrint(){
        var name = "登记关怀单"
        DownloadUtil.get().download(url,
                Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download",
                name + ".pdf", object : DownloadUtil.OnDownloadListener {
            override fun onDownloadSuccess(file: File) {
                DemoLog.v("DOWN", "下載成功,文件已存入手机内部存储设备根目录下Download文件夾中")
                val printManager = currentContext?.getSystemService(Context.PRINT_SERVICE) as PrintManager?
                val builder = PrintAttributes.Builder()
                builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
                printManager!!.print(name, MyPrintAdapter(currentContext, file.path, name), builder.build())
                Looper.prepare()//增加部分
                Looper.loop()//增加部分
            }

            override fun onDownloading(progress: Int) {
                DemoLog.v("DOWN", "下載進度$progress")
            }

            override fun onDownloadFailed(e: Exception) {
                DemoLog.v("DOWN", e.toString())
                MyToast("下载登记关怀单失败")
            }
        })
    }

    fun cancelPrint(){

    }

    /**
     * 弹窗回调
     */
    fun popOk() {
        follow?.apply {
            if (context != null) {
                var intent = Intent(context, DefeatDetailsActivity::class.java)
                if(follow!!.tid.isNullOrEmpty()){
                    intent.putExtra("revkey", follow!!.revkey)
                }else {
                    intent.putExtra("tid", follow!!.tid)
//                    if(follow!!.revkey.isNullOrEmpty()){
//                        intent.putExtra("revkey", follow!!.revkey)
//                    }
                }
                if(follow!!.revkey.equals("follow") || follow!!.revkey.equals("followtip")){
                    intent.putExtra("nkey", "archive.purge")  // 跟进，订车，线索移交
                }else{
//                    intent.putExtra("nkey", "archivepot.index")  // 拨号，激活
                    //拨号，激活 由state ,revkey控制
                    intent.putExtra("nkey", "archive.purge")  // 拨号，激活
                }
                context!!.startActivity(intent)
            }

        }
    }
}
